package com.itcast.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * 对象序列化工具
 *
 * @author eternity
 */
public class ObjectSerializerUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ObjectSerializerUtils.class);

    /**
     * 将字节流序列化为对象-->反序列化
     *
     * @param data 字节流数据
     * @return 对象实体
     */
    public static Object deSerializer(byte[] data) {
        if (data == null || data.length == 0) {
            LOGGER.error("反序列化入参为空");
            return null;
        }
        Object object = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(data);
            ObjectInputStream ois = new ObjectInputStream(bis);
            object = ois.readObject();
        } catch (Exception e) {
            LOGGER.error("反序列化异常：{}", e.getMessage());
        }
        return object;
    }

    /**
     * 将对象转为字节流对象-->序列化
     *
     * @param object 对象实例
     * @return 字节流对象
     */
    public static byte[] serializer(Object object) {
        if (object == null) {
            LOGGER.error("序列化参数为空");
        }
        byte[] bytes = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(object);
            oos.flush();
            oos.close();
            bytes = bos.toByteArray();
        } catch (IOException e) {
            LOGGER.error("序列化异常：{}", e.getMessage());
        }
        return bytes;
    }
}
